package com.unione.unione_base.view

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.AppUtils
import kotlinx.coroutines.CoroutineScope
import java.util.LinkedList

open class AppBaseActivity : AppCompatActivity() {

    private val REQUEST_CODE_PERMISSION = 1

    val isActive: Boolean
        get() = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)

    val mContext: Context
        get() = this

    val mLifecycleOwner: LifecycleOwner
        get() = this

    val scope: CoroutineScope
        get() = lifecycleScope

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        hideStatusBar()
        hideAppBar()
        requestPermissionsIfAboveM()

        // hideNavigation()
    }

    private val permissionHintMap = mutableMapOf<String, String?>()
    private fun requestPermissionsIfAboveM() {
        val requiredPermissions: MutableMap<String, String> = HashMap()
        requiredPermissions[Manifest.permission.WRITE_EXTERNAL_STORAGE] = "写入存储"
        //  requiredPermissions[Manifest.permission.ACCESS_FINE_LOCATION] = "定位"
        // requiredPermissions[Manifest.permission.ACCESS_COARSE_LOCATION] = "定位"
        //  requiredPermissions[Manifest.permission.READ_PHONE_STATE] = "读取存储"
        // requiredPermissions[Manifest.permission.WRITE_SETTINGS] = "系统设置"
        requiredPermissions[Manifest.permission.READ_EXTERNAL_STORAGE] = "读取外部存储"
        requiredPermissions[Manifest.permission.RECORD_AUDIO] = "录音"
        requiredPermissions[Manifest.permission.INTERNET] = "网络"
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//            requiredPermissions[Manifest.permission.MANAGE_EXTERNAL_STORAGE] = "存储"
//        }

        for (permission in requiredPermissions.keys) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                permissionHintMap[permission] = requiredPermissions[permission]
            }
        }
        if (permissionHintMap.isNotEmpty()) {
            requestPermissions(permissionHintMap.keys.toTypedArray(), REQUEST_CODE_PERMISSION)
        } else {
            onPermissionGranted()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val failPermissions: MutableList<String> = LinkedList()
        for (i in grantResults.indices) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                failPermissions.add(permissions[i])
            }
        }
        if (failPermissions.isNotEmpty()) {
            val sb = StringBuilder()
            for (permission in failPermissions) {
                sb.append(permissionHintMap[permission]).append("、")
            }
            sb.deleteCharAt(sb.length - 1)
            val hint = "未授予必要权限: " +
                    sb.toString() +
                    "，请前往设置页面开启权限"
            AlertDialog.Builder(this)
                .setMessage(hint)
                .setNegativeButton("取消") { dialog, which -> System.exit(0) }
                .setPositiveButton("设置") { dialog, which ->
                    val intent = Intent()
                    intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    val uri = Uri.fromParts("package", packageName, null)
                    intent.data = uri
                    startActivity(intent)
                    System.exit(0)
                }.show()
        } else {
            onPermissionGranted()
        }
    }

    open fun onPermissionGranted() {

    }




    fun restartApp() {
        AppUtils.relaunchApp(true)
    }


    @CallSuper
    override fun onContentChanged() {
        super.onContentChanged()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                onTouchScreen()
            }

            MotionEvent.ACTION_UP -> onPointLeaveScreen()
        }
        return super.dispatchTouchEvent(ev)
    }

    open fun onTouchScreen() {

    }

    open fun onPointLeaveScreen() {

    }

    /**
     * 隐藏导航栏
     */
    private fun hideNavigation() {
        WindowCompat.getInsetsController(window, window.decorView).run {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                hide(WindowInsetsCompat.Type.navigationBars())
            }
            systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    private fun hideStatusBar() {
        var flags: Int = 0
        var curApiVersion = Build.VERSION.SDK_INT
        // This work only for android 4.4+
        if (curApiVersion >= Build.VERSION_CODES.KITKAT) {

            // This work only for android 4.4+
            // hide navigation bar permanently in android activity
            // touch the screen, the navigation bar will not show

            flags =
                View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        } else {
            // touch the screen, the navigation bar will show
            flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        }

        // must be executed in main thread :)
        window.decorView.systemUiVisibility = flags

//        if (Build.VERSION.SDK_INT < 16) {
//            window.setFlags(
//                WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN
//            )
//        } else {
//            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
//            // Remember that you should never show the action bar if the
//            // status bar is hidden, so hide that too if necessary.
//            actionBar?.hide()
//        }
    }

    private fun getNavigationBarsHeight(): Int? =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            ViewCompat.getRootWindowInsets(findViewById<FrameLayout>(android.R.id.content))
                ?.getInsets(
                    WindowInsetsCompat.Type.navigationBars()
                )?.bottom
        } else {
            0
        }

    //隐藏虚拟按键，并且全屏
    private  fun hideAppBar() {
        val decorView = window.decorView
        val uiOptions = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE)
        decorView.systemUiVisibility = uiOptions
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        window.setFormat(PixelFormat.TRANSLUCENT)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }


}